package com.atguigu.ting.realtime.app.dws;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.ting.realtime.app.BaseApp;
import com.atguigu.ting.realtime.bean.AlbumPlayBean;
import com.atguigu.ting.realtime.common.Constant;
import com.atguigu.ting.realtime.funtion.DimAsyncFunction;
import com.atguigu.ting.realtime.util.AtguiguUtil;
import com.atguigu.ting.realtime.util.FlinkSinkUtil;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.AsyncDataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;
import java.util.concurrent.TimeUnit;

/**
 * @Author lzc
 * @Date 2023/4/14 12:49
 */
public class DwsAlbumPlayWindow extends BaseApp {
    public static void main(String[] args) {
        new DwsAlbumPlayWindow().init(
            40005,
            2,
            "DwsAlbumPlayWindow",
            Constant.TOPIC_DWD_TRAFFIC_PLAY
        );
    }
    
    @Override
    public void handle(StreamExecutionEnvironment env,
                       DataStreamSource<String> stream) {
        // 1. 解析成 pojo 类型
        SingleOutputStreamOperator<AlbumPlayBean> beanStream = parseToPojo(stream);
        // 2. 开窗聚合
        SingleOutputStreamOperator<AlbumPlayBean> beanStreamWithoutDims = windowAndAgg(beanStream);
        // 3. 补充维度信息
        SingleOutputStreamOperator<AlbumPlayBean> beanStreamWithDims = joinDim(beanStreamWithoutDims);
        // 4. 写出到 clickhouse
        writeToClickhouse(beanStreamWithDims);
    }
    
    private void writeToClickhouse(SingleOutputStreamOperator<AlbumPlayBean> beanStreamWithDims) {
        beanStreamWithDims.addSink(FlinkSinkUtil.getClickHouseSink("dws_album_play_window", AlbumPlayBean.class));
    }
    
    private SingleOutputStreamOperator<AlbumPlayBean> joinDim(SingleOutputStreamOperator<AlbumPlayBean> beanStreamWithoutDims) {
        SingleOutputStreamOperator<AlbumPlayBean> albumStream = AsyncDataStream.unorderedWait(
            beanStreamWithoutDims,
            new DimAsyncFunction<AlbumPlayBean>() {
                @Override
                public void addDim(AlbumPlayBean bean,
                                   JSONObject dim) {
                    bean.setAlbumName(dim.getString("ALBUM_TITLE"));
                    bean.setCategory1Id(dim.getString("CATEGORY1_ID"));
                    bean.setCategory2Id(dim.getString("CATEGORY2_ID"));
                    if (dim.getString("CATEGORY3_ID")==null) {
                        System.out.println(dim);
                    }else{
                        System.out.println("dim: " + dim);
                    }
                    bean.setCategory3Id(dim.getString("CATEGORY3_ID"));
                }
            
                @Override
                public String getId(AlbumPlayBean bean) {
                    return bean.getAlbumId();
                }
            
                @Override
                public String getTable() {
                    return "dim_album_info";
                }
            },
            60,
            TimeUnit.SECONDS
        );
        SingleOutputStreamOperator<AlbumPlayBean> c3Stream = AsyncDataStream.unorderedWait(
            albumStream,
            new DimAsyncFunction<AlbumPlayBean>() {
                @Override
                public void addDim(AlbumPlayBean bean,
                                   JSONObject dim) {
                   bean.setCategory3Name(dim.getString("NAME"));
                }
            
                @Override
                public String getId(AlbumPlayBean bean) {
                    return bean.getCategory3Id();
                }
            
                @Override
                public String getTable() {
                    return "dim_base_category3";
                }
            },
            60,
            TimeUnit.SECONDS
        );
        SingleOutputStreamOperator<AlbumPlayBean> c2Stream = AsyncDataStream.unorderedWait(
            c3Stream,
            new DimAsyncFunction<AlbumPlayBean>() {
                @Override
                public void addDim(AlbumPlayBean bean,
                                   JSONObject dim) {
                    bean.setCategory2Name(dim.getString("NAME"));
                }
            
                @Override
                public String getId(AlbumPlayBean bean) {
                    return bean.getCategory2Id();
                }
            
                @Override
                public String getTable() {
                    return "dim_base_category2";
                }
            },
            60,
            TimeUnit.SECONDS
        );
        return AsyncDataStream.unorderedWait(
            c2Stream,
            new DimAsyncFunction<AlbumPlayBean>() {
                @Override
                public void addDim(AlbumPlayBean bean,
                                   JSONObject dim) {
                    bean.setCategory1Name(dim.getString("NAME"));
                }
        
                @Override
                public String getId(AlbumPlayBean bean) {
                    return bean.getCategory1Id();
                }
        
                @Override
                public String getTable() {
                    return "dim_base_category1";
                }
            },
            60,
            TimeUnit.SECONDS
        );
    }
    
    private SingleOutputStreamOperator<AlbumPlayBean> windowAndAgg(SingleOutputStreamOperator<AlbumPlayBean> beanStream) {
      return  beanStream
            .assignTimestampsAndWatermarks(
                WatermarkStrategy
                    .<AlbumPlayBean>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                    .withTimestampAssigner((bean, ts) -> bean.getTs())
                    .withIdleness(Duration.ofSeconds(60))
            )
            .keyBy(AlbumPlayBean::getAlbumId)
            .window(TumblingEventTimeWindows.of(Time.seconds(5)))
            .reduce(
                new ReduceFunction<AlbumPlayBean>() {
                    @Override
                    public AlbumPlayBean reduce(AlbumPlayBean value1,
                                                AlbumPlayBean value2) throws Exception {
                        value1.setUserCt(value1.getUserCt() + value2.getUserCt());
                        value1.setPlayCt(value1.getPlayCt() + value2.getPlayCt());
                        value1.setPlaySeconds(value1.getPlayCt() + value2.getPlaySeconds());
                        return value1;
                    }
                },
                new ProcessWindowFunction<AlbumPlayBean, AlbumPlayBean, String, TimeWindow>() {
                    @Override
                    public void process(String albumId,
                                        Context ctx,
                                        Iterable<AlbumPlayBean> elements,
                                        Collector<AlbumPlayBean> out) throws Exception {
                        AlbumPlayBean bean = elements.iterator().next();
    
                        bean.setStt(AtguiguUtil.tsToDateTime(ctx.window().getStart()));
                        bean.setEdt(AtguiguUtil.tsToDateTime(ctx.window().getEnd()));
                        bean.setTs(System.currentTimeMillis());
    
                        out.collect(bean);
                    }
                }
            );
    }
    
    private SingleOutputStreamOperator<AlbumPlayBean> parseToPojo(DataStreamSource<String> stream) {
        return stream
            .map(JSONObject::parseObject)
            .keyBy(obj -> obj.getString("user_id") + "_" + obj.getString("album_id"))
            .process(new KeyedProcessFunction<String, JSONObject, AlbumPlayBean>() {
                
                private ValueState<String> lastPlayDateState;
                
                @Override
                public void open(Configuration parameters) throws Exception {
                    lastPlayDateState = getRuntimeContext().getState(new ValueStateDescriptor<String>("lastPlayDate", String.class));
                }
                
                @Override
                public void processElement(JSONObject obj,
                                           Context ctx,
                                           Collector<AlbumPlayBean> out) throws Exception {
                    Long startTs = obj.getLong("start_ts");
                    Long endTs = obj.getLong("end_ts");
                    String today = AtguiguUtil.tsToDate(endTs);
                    String lastPlayDate = lastPlayDateState.value();
                    
                    Long userCt = 0L;
                    if (!today.equals(lastPlayDate)) {// 今天该用户首次对该专辑播放
                        userCt = 1L;
                        lastPlayDateState.update(today);
                    }
                    
                    Long playCt = 0L; // 播放一次会产生条日志,找到第一条播放日志
                    // 第一条播放日志的 endTs - startTs=播放时长 其他日志endTs - startTs < 播放时长
                    Long playDurationSec = obj.getLong("play_duration_sec");
                    if (endTs - startTs == playDurationSec * 1000) {
                        playCt = 1L;
                    }
                    
                    if (userCt + playCt > 0) {
                        out.collect(AlbumPlayBean.builder()
                                        .albumId(obj.getString("album_id"))
                                        .userCt(userCt)
                                        .playCt(playCt)
                                        .playSeconds(playDurationSec)
                                        .ts(endTs)
                                        .build());
                    }
                }
            });
    }
}
